package com.itbaizhan.shopping_file_service.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itbaizhan.shopping_common.result.BusException;
import com.itbaizhan.shopping_common.result.CodeEnum;
import com.itbaizhan.shopping_common.service.FileService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;

@DubboService
public class FileServiceImpl implements FileService {
    @Autowired
    private FastFileStorageClient storageClient;
    @Value("${fdfs.fileUrl}")
    private String fileUrl;

    @Override
    public String uploadFile(byte[] fileBytes, String fileName) {
        if (fileBytes.length != 0) {
            try {
                // 1、将文件数组转换为输入流
                ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
                //2、获取文件后缀
                String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                //3、上传文件
                StorePath storePath = storageClient.uploadFile(inputStream, inputStream.available(), fileSuffix, null);
                //返回文件路径
                String imagePath = fileUrl + "/" + storePath.getFullPath();
                return imagePath;
            } catch (Exception e) {
                throw new BusException(CodeEnum.FILE_UPLOAD_ERROR);
            }

        } else {
            throw new BusException(CodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @Override
    public void deleteFile(String filePath) {
        storageClient.deleteFile(filePath);
    }
}
